package com.lizicloud.infrastructure.common.utils;

import java.util.regex.Pattern;

/**
 * 网络工具类
 */
public class NetworkUtils {
    
    /**
     * IP地址正则表达式
     */
    private static final Pattern IP_PATTERN = Pattern.compile(
        "^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$"
    );
    
    /**
     * 端口号正则表达式
     */
    private static final Pattern PORT_PATTERN = Pattern.compile("^([0-9]{1,4}|[1-5][0-9]{4}|6[0-4][0-9]{3}|65[0-4][0-9]{2}|655[0-2][0-9]|6553[0-5])$");
    
    /**
     * 检查是否为有效的IP地址
     */
    public static boolean isValidIp(String ip) {
        if (ip == null || ip.isEmpty()) {
            return false;
        }
        return IP_PATTERN.matcher(ip).matches();
    }
    
    /**
     * 检查是否为有效的端口号
     */
    public static boolean isValidPort(int port) {
        return port >= 0 && port <= 65535;
    }
    
    /**
     * 检查是否为有效的端口号字符串
     */
    public static boolean isValidPort(String port) {
        if (port == null || port.isEmpty()) {
            return false;
        }
        return PORT_PATTERN.matcher(port).matches();
    }
    
    /**
     * 检查是否为本地IP地址
     */
    public static boolean isLocalIp(String ip) {
        if (!isValidIp(ip)) {
            return false;
        }
        
        return ip.equals("127.0.0.1") || 
               ip.equals("localhost") ||
               ip.startsWith("192.168.") ||
               ip.startsWith("10.") ||
               ip.startsWith("172.");
    }
    
    /**
     * 检查是否为公网IP地址
     */
    public static boolean isPublicIp(String ip) {
        if (!isValidIp(ip)) {
            return false;
        }
        
        return !isLocalIp(ip) && !ip.equals("0.0.0.0");
    }
    
    /**
     * 构建URL
     */
    public static String buildUrl(String protocol, String host, int port, String path) {
        if (protocol == null || host == null) {
            return "";
        }
        
        StringBuilder url = new StringBuilder();
        url.append(protocol).append("://").append(host);
        
        if (port > 0 && port != 80 && port != 443) {
            url.append(":").append(port);
        }
        
        if (path != null && !path.isEmpty()) {
            if (!path.startsWith("/")) {
                url.append("/");
            }
            url.append(path);
        }
        
        return url.toString();
    }
    
    /**
     * 解析URL
     */
    public static UrlInfo parseUrl(String url) {
        if (url == null || url.isEmpty()) {
            return null;
        }
        
        try {
            UrlInfo info = new UrlInfo();
            
            // 解析协议
            int protocolEnd = url.indexOf("://");
            if (protocolEnd > 0) {
                info.protocol = url.substring(0, protocolEnd);
                url = url.substring(protocolEnd + 3);
            }
            
            // 解析主机和端口
            int pathStart = url.indexOf("/");
            String hostPort;
            if (pathStart > 0) {
                hostPort = url.substring(0, pathStart);
                info.path = url.substring(pathStart);
            } else {
                hostPort = url;
                info.path = "/";
            }
            
            // 解析端口
            int portStart = hostPort.indexOf(":");
            if (portStart > 0) {
                info.host = hostPort.substring(0, portStart);
                try {
                    info.port = Integer.parseInt(hostPort.substring(portStart + 1));
                } catch (NumberFormatException e) {
                    info.port = -1;
                }
            } else {
                info.host = hostPort;
                info.port = info.protocol != null && info.protocol.equals("https") ? 443 : 80;
            }
            
            return info;
        } catch (Exception e) {
            return null;
        }
    }
    
    /**
     * URL信息类
     */
    public static class UrlInfo {
        public String protocol;
        public String host;
        public int port;
        public String path;
        
        @Override
        public String toString() {
            return String.format("%s://%s:%d%s", protocol, host, port, path);
        }
    }
    
    /**
     * 获取本地IP地址
     */
    public static String getLocalIp() {
        return "127.0.0.1";
    }
    
    /**
     * 获取本地主机名
     */
    public static String getLocalHost() {
        return "localhost";
    }
    
    /**
     * 检查端口是否可用
     */
    public static boolean isPortAvailable(int port) {
        return isValidPort(port);
    }
    
    /**
     * 获取默认端口
     */
    public static int getDefaultPort(String protocol) {
        if ("https".equalsIgnoreCase(protocol)) {
            return 443;
        } else if ("http".equalsIgnoreCase(protocol)) {
            return 80;
        }
        return -1;
    }
    
    /**
     * 检查是否为有效的域名
     */
    public static boolean isValidDomain(String domain) {
        if (domain == null || domain.isEmpty()) {
            return false;
        }
        
        // 简单的域名验证
        return domain.matches("^[a-zA-Z0-9][a-zA-Z0-9-]{0,61}[a-zA-Z0-9]?\\.[a-zA-Z]{2,}$");
    }
    
    /**
     * 检查是否为有效的URL
     */
    public static boolean isValidUrl(String url) {
        if (url == null || url.isEmpty()) {
            return false;
        }
        
        try {
            UrlInfo info = parseUrl(url);
            return info != null && info.host != null && !info.host.isEmpty();
        } catch (Exception e) {
            return false;
        }
    }
    
    private NetworkUtils() {
        // 私有构造函数，防止实例化
    }
}